//
//  BVChangeCityViewController.m
//  BuyVegetable
//
//  Created by yushanchang on 16/10/14.
//  Copyright © 2016年 com.yinding. All rights reserved.
//

#import "BVChangeCityViewController.h"
#import <AMapFoundationKit/AMapFoundationKit.h>
#import <AMapLocationKit/AMapLocationKit.h>

#import "BVChangeCityLocationCell.h"
#import "BVChangeCityHeader.h"
#import "UIBarButtonItem+BVItem.h"
#import "BVIndexTool.h"
#import "BVSelectArea.h"
#import "BVSelectCityViewController.h"
#import "BVNavItem.h"

#define CHANGECITYCELL_IDENTIFIER @"BVChangeCityLocationCell"
#define LOCATED_CITY @"定位城市"
#define CURRENT_CITY @"当前城市"
#define ALL_CITY     @"按省份选择城市"


@interface BVChangeCityViewController ()<UITableViewDelegate,UITableViewDataSource,AMapLocationManagerDelegate>
@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (nonatomic, strong) AMapLocationManager *locationManager;
@property (nonatomic, copy) NSString *currentCity;
@property (nonatomic, copy) NSString *locatedCity;
@property (nonatomic, strong) BVIndexTool *indexTool;
@property (nonatomic, strong) NSArray *dataSource;
@property (nonatomic, strong) BVNavItem *navItem;

@end

@implementation BVChangeCityViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self.navigationItem setTitle:@"选择地区"];
    [self setupNavLeftItem];
    [self getLoactionInformation];
    [self fetchAreaData];
}

- (void)fetchAreaData {
//    [self showLoading];
    [self.indexTool fetchAllProvinceSuccess:^(NSArray *provinces) {
//        [self hideHUD];
        self.dataSource = provinces;
        [self.tableView reloadData];
    } failure:^(NSError *error) {
        [self showMessage:@"网络错误"];
    }];
}

- (AMapLocationManager *)locationManager {
    if (!_locationManager) {
        _locationManager = [[AMapLocationManager alloc] init];
        
        [_locationManager setDelegate:self];
        // 带逆地理信息的一次定位（返回坐标和地址信息）
        [_locationManager setDesiredAccuracy:kCLLocationAccuracyHundredMeters];
        [_locationManager setDistanceFilter:10.f];
        // 定位超时时间
        [_locationManager setLocationTimeout:5.f];
        // 逆地理请求超时时间
        [_locationManager setReGeocodeTimeout:3.f];
    }
    return  _locationManager;
}

- (NSString *)currentCity{
    _currentCity = self.user.city;
    if (! _currentCity) {
        _currentCity = @"未选择";
    }
    return _currentCity;
}

- (NSString *)locatedCity {
    if (!_locatedCity) {
        _locatedCity = @"定位中";
    }
    return _locatedCity;
}

- (void)setupNavLeftItem {
//    self.navigationItem.leftBarButtonItem = [UIBarButtonItem barButtonItemWithImage:[UIImage imageNamed:@"back_3"] target:self action:@selector(navigationBackClick) forControlEvents:UIControlEventTouchUpInside];
    
    self.navItem = [[BVNavItem alloc] initWithFrame:CGRectMake(0, 0, 40, 30)];
    [self.navItem setTitle:@"取消" forState:UIControlStateNormal];
    [self.navItem setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [self.navItem addTarget:self action:@selector(cancelClick) forControlEvents:UIControlEventTouchUpInside];
    
    UIBarButtonItem *space = [[UIBarButtonItem alloc] initWithBarButtonSystemItem: UIBarButtonSystemItemFixedSpace target:nil action:nil];
    space.width = -10;
    self.navigationItem.leftBarButtonItems = @[space,[[UIBarButtonItem alloc] initWithCustomView:self.navItem]];
}

- (void)cancelClick {
    
    if (self.user.city) {
        [self dismissViewControllerAnimated:YES completion:nil];
    } else {
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"请选择正确的城市" message:@"请选择城市" preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *confirmAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:nil];
        [alert addAction:confirmAction];
        [self presentViewController:alert animated:YES completion:nil];
    }
//    [self dismissViewControllerAnimated:YES completion:nil];
}

- (void)getLoactionInformation {
    
    [self.locationManager requestLocationWithReGeocode:YES completionBlock:^(CLLocation *location, AMapLocationReGeocode *regeocode, NSError *error) {
        
        if (error){
            if (error.code == (AMapLocationErrorLocateFailed | AMapLocationErrorReGeocodeFailed | AMapLocationErrorUnknown)){
                return;
            }
        }
        if (regeocode){
#warning 定位城市处理！！！
            self.locatedCity = regeocode.city;
        } else {
        self.locatedCity = @"定位失败";
        }
        [self.tableView performSelectorOnMainThread:@selector(reloadData) withObject:nil waitUntilDone:YES];
    }];
}

- (void)dealloc {
    //停止定位
    [self.locationManager stopUpdatingLocation];
    [self.locationManager setDelegate:nil];
}

#pragma mark -
#pragma mark - UITableViewDelegate,UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 3;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return section <= 1 ? 1 : self.dataSource.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    BVChangeCityLocationCell *changeCityCell = [tableView dequeueReusableCellWithIdentifier:CHANGECITYCELL_IDENTIFIER];
    
    if (!changeCityCell) {
        if (indexPath.section <= 1) {
            changeCityCell = [[NSBundle mainBundle] loadNibNamed:CHANGECITYCELL_IDENTIFIER owner:self options:nil][0];
            
            if (indexPath.section == 0) {
                [changeCityCell.locatedBtn setTitle:self.locatedCity forState:UIControlStateNormal];
                changeCityCell.clickBlock = ^(UIButton *button){
                    [self showAlert:button];
                };
            } else if (indexPath.section == 1) {
                [changeCityCell.locatedBtn setTitle:self.currentCity forState:UIControlStateNormal];
                changeCityCell.clickBlock = ^(UIButton *button){
                    [self showAlert:button];
                };
            }
            
        } else {
            changeCityCell = [[NSBundle mainBundle] loadNibNamed:CHANGECITYCELL_IDENTIFIER owner:self options:nil][1];
            changeCityCell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
            BVSelectArea *selectArea = self.dataSource[indexPath.row];
            changeCityCell.sectionThreeLabel.text = selectArea.names;
        }
    }
    return changeCityCell;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {

    BVChangeCityHeader *headerView = [BVChangeCityHeader initWithOwner:self];
    if (section == 0) {
        headerView.cityHeader.text = LOCATED_CITY;
        headerView.picture.image = IMAGE_NAMED(@"located");
    } else if (section == 1){
        headerView.cityHeader.text = CURRENT_CITY;
        headerView.picture.image = IMAGE_NAMED(@"current2");
    } else {
        headerView.cityHeader.text = ALL_CITY;
        headerView.picture.image = IMAGE_NAMED(@"province");
    }
    return headerView;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    if (indexPath.section == 2) {
        BVSelectArea *selectArea = self.dataSource[indexPath.row];
        BVSelectCityViewController *select_city = [[BVSelectCityViewController alloc] init];
        select_city.selectArea = selectArea;
        select_city.city = selectArea.cities;
        [self.navigationController pushViewController:select_city animated:YES];
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 35;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 0.01;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 40;
}

#pragma mark - 
#pragma mark - 判断选择的城市是否有效
- (void)showAlert:(UIButton *)button {
    
    NSString *buttonTitle = button.titleLabel.text;
    if ([buttonTitle isEqualToString:@""] || !buttonTitle || [buttonTitle isEqualToString:@"定位中"] || [buttonTitle isEqualToString: @"定位失败"] || [buttonTitle isEqualToString:@"未选择"]) {
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"请选择正确的城市" message:@"请选择城市" preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *confirmAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:nil];
        [self.user setCity:nil];
        [alert addAction:confirmAction];
        [self presentViewController:alert animated:YES completion:nil];
    } else {
        [self.user setCity:button.titleLabel.text city_id:@""];
        [self.navigationController popViewControllerAnimated:YES];
    }
}


- (BVIndexTool *)indexTool {
    if (!_indexTool) {
        _indexTool = [[BVIndexTool alloc] init];
    }
    return _indexTool;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}


@end
